import smtplib
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart


class SendEmail:
    def __init__(self, from_addr, password, smtp_host, smtp_port):
        self.__smtp_port = smtp_port
        self.__smtp_host = smtp_host
        self.__password = password
        self.__from_addr = from_addr

    def send_html_email(self, to_addr, subject, context):
        msg = MIMEText(context, 'html', 'utf-8')
        msg.add_header("From", self.__from_addr)
        msg.add_header("To", to_addr)
        msg.add_header("Subject", subject)
        try:
            smtp = smtplib.SMTP_SSL(self.__smtp_host, self.__smtp_port)
            smtp.login(self.__from_addr, self.__password)
            smtp.sendmail(self.__from_addr, to_addr, msg.as_string())
            smtp.quit()
            print("邮件发送成功！")
        except Exception as e:
            print("邮件发送失败！原因：", e)

    def send_attach_mail(self, to_addr, subject, context, files):
        msg = MIMEMultipart()
        msg.attach(MIMEText(context, 'html', 'utf8'))
        msg.add_header("From", self.__from_addr)
        msg.add_header("Subject", subject)
        msg.add_header("To", to_addr)

        for file in files:
            with open(file, 'rb') as f:
                at = MIMEText(open(file, 'rb').read(), 'base64', 'utf8')
                at.add_header("Content-Type", 'application/octet-stream')
                at.add_header("Content-Disposition", f'attachment; filename={file}')
                msg.attach(at)
        try:
            smtp = smtplib.SMTP_SSL(self.__smtp_host, self.__smtp_port)
            smtp.login(self.__from_addr, self.__password)
            smtp.sendmail(from_addr=self.__from_addr, to_addrs=to_addr, msg=msg.as_string())
            print("发送成功！")
        except Exception as e:
            print("发送失败！原因：", e)


if __name__ == '__main__':
    se = SendEmail("itian932@foxmail.com", "bomfwrgmtxbpdieb", "smtp.qq.com", 465)
    # se.send_html_email("itian932@163.com", "邮箱测试", "<a href='www.baidu.com'>百度</a>")
    se.send_attach_mail("itian932@163.com", "邮箱测试", "<a href='www.baidu.com'>百度</a>", ["test.xlsx", "test.yaml"])
